package com.example.networktest

import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread

object HttpUtil {
    private val client = OkHttpClient().newBuilder()
        .connectTimeout(8, TimeUnit.SECONDS)
        .readTimeout(8, TimeUnit.SECONDS)
        .build()

    fun sendHttpRequest(address: String, callback: HttpCallbackListener) {
        thread {
            var connect: HttpURLConnection? = null
            try {
                val url = URL(address)
                connect = url.openConnection() as HttpURLConnection
                connect.connectTimeout = 8000
                connect.readTimeout = 8000
                val inputStream = connect.inputStream
                val bufferedReader = BufferedReader(InputStreamReader(inputStream))
                val str = StringBuilder()
                bufferedReader.use {
                    bufferedReader.forEachLine {
                        str.append(it)
                    }
                }
                callback.onFinish(str.toString())
            } catch (e: Exception) {
                e.printStackTrace()
                callback.onError(e)
            } finally {
                connect?.disconnect()
            }
        }
    }

    fun sendHttpRequestWithOkHttp(address: String, callback: okhttp3.Callback) {
        try {
            val request = Request.Builder()
                .url(address)
                .build()
            client.newCall(request).enqueue(callback)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}